import request from './service'
import { Message } from 'element-ui'

function http({ url, data, method, headers, onDownloadProgress, signal, beforeRequest, afterRequest }) {
  const successHandler = (res) => {
    if (res.data.code === 0 || res.data.code === 200 || typeof res.data === 'string') {
      return res.data.result
    }
    Message.error(res.data.message || res.data.text || 'Error')
    return Promise.reject(res.data.result)
  }
  const failHandler = async(error) => {
    afterRequest?.()
    if (!error.response) {
      Message.error('Error')
      throw new Error('Error')
    }
    Message.error(error.message || 'Error')
    throw new Error(error.message || 'Error')
  }

  beforeRequest?.()
  method = method || 'GET'
  const params = Object.assign(typeof data === 'function' ? data() : data ?? {}, {})
  const controller = new AbortController()
  const requestOptions = {
    signal: controller.signal,
    params,
    onDownloadProgress
  }
  const requestPromise =
    method === 'GET'
      ? request.get(url, { headers, ...requestOptions })
      : request.post(url, params, { headers, ...requestOptions })

  const resultPromise = requestPromise.then(successHandler, failHandler)

  if (signal && signal.addEventListener) {
    signal.addEventListener('abort', () => {
      controller.abort()
    })
  }

  return resultPromise
}

export function get({ url, data, method = 'GET', onDownloadProgress, signal, beforeRequest, afterRequest }) {
  return http({
    url,
    method,
    data,
    onDownloadProgress,
    signal,
    beforeRequest,
    afterRequest
  })
}

export function post({ url, data, method = 'POST', headers, onDownloadProgress, signal, beforeRequest, afterRequest }) {
  return http({
    url,
    method,
    data,
    headers,
    onDownloadProgress,
    signal,
    beforeRequest,
    afterRequest
  })
}

export default post
